package fr.norsys.mapper.console.web;

import java.io.InputStream;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import fr.norsys.mapper.console.model.Application;
import fr.norsys.mapper.console.model.ConsoleCst;
import fr.norsys.mapper.console.service.ApplicationService;
import fr.norsys.mapper.console.service.MappingService;

public class UploadFileAction extends BaseAppDispatchAction {
	private MappingService mappingService;
	private ApplicationService applicationService;
	public ApplicationService getApplicationService() {
		return applicationService;
	}
	public void setApplicationService(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}
	public MappingService getMappingService() {
		return mappingService;
	}
	public void setMappingService(MappingService mappingService) {
		this.mappingService = mappingService;
	}
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UploadForm uploadForm = (UploadForm) form;
		FormFile file = uploadForm.getFile();
		InputStream stream = file.getInputStream();
		String applicationId = (String) request.getSession().getAttribute(ConsoleCst.APPLICATION_ID); 
		Application application = applicationService.get(applicationId,(Collection)request.getSession().getAttribute(ConsoleCst.APPLICATIONS_SESSION_BEAN));
		mappingService.importApplicationConfig(application,stream);
		stream.close();
		file.destroy();
		request.setAttribute("retUpload","true");
		request.getSession().setAttribute(ConsoleCst.IS_APPLICATION_MODIFIED,ConsoleCst.APPLICATION_MODIFIED);
		return mapping.findForward("index");
	}
}
